import { toLogin } from "@/utils";
import token from "../utils/token";
import { customerService } from "@/utils/service";
import session from "@/utils/session";
import system from "@/utils/system";
import md5 from 'js-md5'

//const baseurl = 'http://118.31.168.104:7001/' // 调试环境
//const baseurl = 'http://118.31.168.104:8080/' // 测试环境
const baseurl = 'https://www.taojingshou.com/'  // 生产环境
const appSecret = 'f0d16675bd2ebf1a'

function api(name, params) {
	const queryString = params ? '?' + Object.entries(params)
	   .filter(([key, value]) => key && value)
	  .map(([key, value]) => `${key}=${value}`)
	  .join('&') : '';
	return `${baseurl}app/api/${name}${queryString}`
}

export function baseUrl(url) {
	if (url) {
		const regex = /^(http|https):\/\//;
		if (regex.test(url)) {
			return url;
		} else {
			return baseurl.replace(/\/$/, '') + '/' + url.replace(/^\//, '').replace(/\\/g, '/');
		}
	}
	
	return url;
}

function signParams(params) {
	params = params || {}
	const signedParams = { ...params }

	if (!signedParams.timestamp) {
		signedParams.timestamp = Math.floor(Date.now() / 1000).toString()
	}

	let sb = ''
	const keys = Object.keys(signedParams).sort()
	for (const key of keys) {
		if (key === 'sign') continue
		sb += key + String(signedParams[key])
	}

	sb += appSecret
	signedParams.sign = md5(sb).toLowerCase()
	return signedParams
}

function checkResponse(res) {	
	if (res.statusCode !== 200) {
		uni.showToast({
			title: res.errMsg,
			icon:'none'
		})
		
		return false;
	}
	
	if (res.data.code === 2000) {
		return true;
	}
	
	if (res.data.code == 10001) {
		token.clear();
		uni.showModal({
			title: '警告',
			content: res.data.msg,
			showCancel:false,
			success: function (res) {
				uni.reLaunch({
					url:'/pages/index/index'
				})
				this.$store.state.tabIndex = 0;
			}
		});
		
		return false;
	}
	
	if (res.data.code == 10002 || res.data.code === 401) {
		getApp().globalData.toast = '登录信息失效，请重新登录！'
		token.clear();
		
		toLogin();
		
		return false;
	}
	
	if (res.data.code == 10004) {
		uni.showModal({
			title: '警告',
			content: res.data.msg,
			showCancel:false
		});
		return false;
	}
	
	uni.showToast({
		title: res.data.msg,
		icon:'none'
	})
	
	return false;
}

export async function refreshToken(ensure) {
	if (!token.refresh) return;
	
	if (!ensure && !token.needRefresh()) return;
	
	return new Promise((resolve, reject) => {
		uni.request({
			method:'POST',
			url: api('token/refresh/'),
			data: signParams({
				refresh: token.refresh
			}),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) {
					token.clear();
					return;
				}
				
				token.save(res.data);
				resolve(res.data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}

export async function sendSMS(phone, type) {
	return new Promise((resolve, reject) => {
		uni.request({
			method:'POST',
			url: api('send_sms/'),
			data: signParams({
				phone,
				type
			}),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}

export async function alipayAuthLogin(params) {
	return new Promise((resolve, reject) => {
		uni.request({
			method:'POST',
			url: api('alipay-auth-login/'),
			data: signParams({
				params,
				system: JSON.stringify(uni.getSystemInfoSync())
			}),
			header: system.headers(),
			success(res) {
				if (checkResponse(res)) {
					token.save(res.data);
				}
				
				resolve(res.data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}

export async function weixinAuthLogin(params) {
	return new Promise((resolve, reject) => {
		uni.request({
			method:'POST',
			url: api('weixin-auth-login/'),
			data: signParams({
				params,
				system: JSON.stringify(uni.getSystemInfoSync())
			}),
			header: system.headers(),
			success(res) {
				if (checkResponse(res)) {
					token.save(res.data);
				}
				
				resolve(res.data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}

export async function login(phone, code) {
	return new Promise((resolve, reject) => {
		uni.request({
			method:'POST',
			url: api('login/'),
			data: signParams({
				phone,
				code,
				system: JSON.stringify(uni.getSystemInfoSync())
			}),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				
				token.save(res.data);
				resolve(res.data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}

export async function sendSMSAuth(phone, type) {
	return new Promise((resolve, reject) => {
		uni.request({
			method:'POST',
			url: api('auth_send_sms/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({
				phone,
				type
			}),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}

export async function logout() {
	return new Promise((resolve, reject) => {
		uni.request({
			method:'POST',
			url: api('logout/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}

export async function cancelAccount(phone, code) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method:'POST',
			url: api('cancel-account/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({phone, code}),
			success(res) {
				checkResponse(res);
				
				resolve(res.data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}

export async function getConfig() {
	return new Promise((resolve, reject) => {
		uni.request({
			method:'GET',
			url: api('config/'),
			data: signParams(),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				const data = res.data;
				customerService.saveConfig(data.data.kefu_code);
				resolve(data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}

export async function getIndexData() {
	return new Promise((resolve, reject) => {
		uni.request({
			method:'GET',
			url: api('index/'),
			data: signParams(),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				const data = res.data;
				customerService.saveConfig(data.data.kefu_code);
				resolve(data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}


export async function getCategories() {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('card/cateogries/'),
			data: signParams(),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data);
			},
			fail(res) {
				reject(res)
			}
		})
	}) 
}

export async function getDetail(cardId) {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api(`card/${cardId}/`),
			data: signParams(),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}

export async function exchangeCard(id, face_value_id, face_value, card_no, card_pw) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'POST',
			url: api('card/' + id + '/exchange/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({
				face_value_id,
				face_value,
				card_no,
				card_pw
			}),
			success(res) {
				checkResponse(res);
				resolve(res.data);
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function exchangeCards(id, face_value_id, face_value, cards) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'POST',
			url: api('card/' + id + '/exchange-batch/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({
				face_value_id,
				face_value,
				cards
			}),
			success(res) {
				checkResponse(res);
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getOrders(status, page) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('order/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({status, page}),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data);
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getOrderDetail(id) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('order/' + id + '/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data);
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getHotKeywords() {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('keywords/'),
			data: signParams(),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function search(keyword, page) {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('search/'),
			data: signParams({keyword, page}),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function userCenter() {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('member/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data);
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getAuthInfo() {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('auth-info/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getAuthDetail() {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('auth-detail/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function doBaseAuth(name, id_number, phone, code) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'POST',
			url: api('base-auth/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({
				name,
				id_number,
				phone,
				code
			}),
			success(res) {
				checkResponse(res);
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function doAdvanceAuth(front, back) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'POST',
			url: api('advance-auth/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({
				front,
				back
			}),
			success(res) {
				checkResponse(res);
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function uploadImage(filePath) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: api('upload/'),
			filePath,
			name: 'file',
			fileType: 'image',
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			success(res) {
				if (res.data) {
					res.data = JSON.parse(res.data);
				}
				checkResponse(res);
				
				resolve(res.data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
}

export async function getWithdrawInfo() {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('withdraw-info/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function bindAlipayAccount(ali_account) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'POST',
			url: api('bind/aplipay/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({
				ali_account
			}),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getBankList() {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('bank-card/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function addBankCard(branch_name, card_number, is_default) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'POST',
			url: api('bank-card/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({
				branch_name, card_number, is_default
			}),
			success(res) {
				checkResponse(res);
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getBankCard(id) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('bank-card/' + id + '/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function updateBankCard(id, branch_name, card_number, is_default) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'PUT',
			url: api('bank-card/' + id + '/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({
				branch_name, card_number, is_default
			}),
			success(res) {
				checkResponse(res);
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function doWithdraw(amount, withdrawal_method_id, bank_card_id) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'POST',
			url: api('do-withdraw/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({
				amount, withdrawal_method_id, bank_card_id
			}),
			success(res) {
				checkResponse(res);
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getWithdrawRecords(status, page) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('withdrawal-record/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({status, page}),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getWithdrawDetail(id, ignore) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('withdrawal-record/' + id + '/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getBillRecords(type, page) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('bill-record/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({type, page}),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getMessages(type, page) {
	await refreshToken();
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('message/'),
			header: system.headers({
				'authorization': `JWT ${token.access}`
			}),
			data: signParams({type, page}),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getFaqList(page) {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('faq/'),
			data: signParams({page}),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getFaq(id) {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('faq/' + id + '/'),
			data: signParams(),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getAgreement(type) {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('agreement/' + type + '/'),
			data: signParams(),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function feedback(content, phone, type) {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'POST',
			url: api('feedback/'),
			data: signParams({content, phone, type, channel: 2}),
			header: system.headers(),
			success(res) {
				checkResponse(res);
				resolve(res.data);
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getEnterpriseQualification() {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('enterprise-qualification/'),
			data: signParams(),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}

export async function getAboutus() {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: api('about-us/'),
			data: signParams(),
			header: system.headers(),
			success(res) {
				if (!checkResponse(res)) return;
				
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		})
	})
}